import dayjs from "dayjs";
import { resolve } from "path";
import pkg from "./package.json";
import { wrapperEnv } from "./build";
import { getPluginsList } from "./build/plugins";
import { include, exclude } from "./build/optimize";
import { UserConfigExport, ConfigEnv, loadEnv } from "vite";
import os from "os";
import { filterSassWarningsPlugin } from "./build/plugins/filter-sass-warnings";

/** 当前执行node命令时文件夹的地址（工作目录） */
const root: string = process.cwd();

/** 路径查找 */
const pathResolve = (dir: string): string => {
  return resolve(__dirname, ".", dir);
};

/** 设置别名 */
const alias: Record<string, string> = {
  "@": pathResolve("src"),
  "@build": pathResolve("build")
};

const { dependencies, devDependencies, name, version } = pkg;
const __APP_INFO__ = {
  pkg: { dependencies, devDependencies, name, version },
  lastBuildTime: dayjs(new Date()).format("YYYY-MM-DD HH:mm:ss")
};

// 判断当前操作系统
const isWin = os.platform() === "win32";

export default ({ command, mode }: ConfigEnv): UserConfigExport => {
  const { VITE_CDN, VITE_PORT, VITE_COMPRESSION, VITE_PUBLIC_PATH } =
    wrapperEnv(loadEnv(mode, root));
  return {
    base: VITE_PUBLIC_PATH,
    root,
    resolve: {
      alias
    },
    // 设置日志级别为info，显示重要信息
    logLevel: "info",
    // 全局变量处理
    css: {
      preprocessorOptions: {
        scss: {
          // 不使用additionalData注入全局导入，因为可能是导致警告的原因之一
          // 改用直接在sass配置中设置所有可能的抑制警告选项
          sassOptions: {
            quietDeps: true,
            quiet: true,
            verbose: false,
            style: "compressed",
            sourceComments: false,
            alertColor: false,
            noDeprecation: true, // 尝试彻底禁用废弃警告
            // 自定义日志处理器，完全忽略所有警告消息
            logger: {
              warn: function () {
                return;
              },
              debug: function () {
                return;
              },
              error: function (message) {
                // 只保留真正的错误，但过滤包含deprecation的警告
                if (
                  message &&
                  typeof message === "string" &&
                  !message.toLowerCase().includes("deprecation")
                ) {
                  console.error(message);
                }
              }
            }
          }
        }
      },
      // 禁用源映射，可能会减少一些输出
      devSourcemap: false
    },
    // 服务端渲染
    server: {
      // 是否开启 https
      https: false,
      // 端口号
      port: VITE_PORT,
      host: "0.0.0.0",
      // 本地跨域代理 https://cn.vitejs.dev/config/server-options.html#server-proxy
      proxy: {
        "/dev-api": {
          target: "http://localhost:8080",
          changeOrigin: true,
          rewrite: path => path.replace(/^\/dev-api/, "")
        }
      },
      // Windows环境的额外配置
      watch: isWin
        ? {
            usePolling: true // 在Windows上使用轮询可能会更可靠
          }
        : {}
    },
    plugins: [
      filterSassWarningsPlugin(),
      ...getPluginsList(command, VITE_CDN, VITE_COMPRESSION)
    ],
    // https://cn.vitejs.dev/config/dep-optimization-options.html#dep-optimization-options
    optimizeDeps: {
      include,
      exclude
    },
    build: {
      sourcemap: false,
      // 消除打包大小超过500kb警告
      chunkSizeWarningLimit: 4000,
      rollupOptions: {
        input: {
          index: pathResolve("index.html")
        },
        // 静态资源分类打包
        output: {
          chunkFileNames: "static/js/[name]-[hash].js",
          entryFileNames: "static/js/[name]-[hash].js",
          assetFileNames: "static/[ext]/[name]-[hash].[ext]"
        }
      }
    },
    define: {
      __INTLIFY_PROD_DEVTOOLS__: false,
      __APP_INFO__: JSON.stringify(__APP_INFO__)
    }
  };
};
